package com.hsgene.shoppingcar.service.impl;

import com.hsgene.common.ClientType;
import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.coupon.dto.GeneticDiscountDto;
import com.hsgene.coupon.dto.GeneticUserDiscountDto;
import com.hsgene.order.domain.applets.AppletsOrderPackageInfoDto;
import com.hsgene.product.dto.wechat.SimpleCommodityDto;
import com.hsgene.shoppingcar.condition.GeneticTestingOrderCarCondition;
import com.hsgene.shoppingcar.domain.GeneticTestingOrderCar;
import com.hsgene.shoppingcar.dto.DiscountDto;
import com.hsgene.shoppingcar.persistence.GeneticTestingOrderCarPersistence;
import com.hsgene.shoppingcar.service.GeneticTestingOrderCarService;
import com.hsgene.shoppingcar.service.api.DiscountCouponService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.shoppingcar.service.impl
 * @author: maodi
 * @createDate: 2018/10/15 10:49
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@Service
public class GeneticTestingOrderCarServiceImpl implements GeneticTestingOrderCarService {

    private final static Logger LOGGER = LoggerFactory.getLogger(GeneticTestingOrderCarServiceImpl.class);

    @Resource
    GeneticTestingOrderCarPersistence geneticTestingOrderCarPersistence;

    @Resource
    DiscountCouponService discountCouponService;

    /**
     * @param userId 用户id
     * @param userType 用户类型
     * @return int
     * @description 获取购物车商品数量
     * @author maodi
     * @createDate 2018/10/17 13:40
     */
    @Override
    public int getShoppingCarCommodityCount(String userId, Integer userType) {
        return geneticTestingOrderCarPersistence.getShoppingCarCommodityCount(userId, userType);
    }

    /**
     * @param userId 用户id
     * @return int
     * @description 获取购物车每个商品数量加起来值
     * @author maodi
     * @createDate 2018/10/25 9:04
     */
    @Override
    public int getShoppingCarCommodityAmount(String userId) {
        return geneticTestingOrderCarPersistence.getShoppingCarCommodityAmount(userId);
    }

    /**
     * @param userId      用户id
     * @param limitHelper 分页条件
     * @param userType 用户类型
     * @return com.hsgene.common.util.support.Pagination<com.hsgene.product.dto.wechat.SimpleCommodityDto>
     * @description 查询当前购物车商品简要信息列表
     * @author maodi
     * @createDate 2018/10/17 11:56
     */
    @Override
    public Pagination<SimpleCommodityDto> getShoppingCarCommodityList(String userId, LimitHelper limitHelper, Integer userType) {
        int totalCount = geneticTestingOrderCarPersistence.getShoppingCarCommodityCount(userId, userType);
        Pagination<SimpleCommodityDto> pagination = Pagination.newInstance(limitHelper, totalCount);
        List<SimpleCommodityDto> result = geneticTestingOrderCarPersistence.getShoppingCarCommodityList(userId,
                limitHelper, userType);
        dealResult(result, userId);
        for (SimpleCommodityDto dto : result) {
            String oldUrl = dto.getCommodityImagesUrl();
            if (org.apache.commons.lang.StringUtils.isNotBlank(oldUrl)) {
                String newUrl = QiniuCertificateUtil.getDownloadCertificateStr(oldUrl);
                dto.setCommodityImagesUrl(newUrl);
            }
        }
        pagination.setResult(result);
        return pagination;
    }

    /**
     * @param userId 用户id
     * @param ids    商品id数组
     * @return java.util.List<com.hsgene.product.dto.wechat.SimpleCommodityDto>
     * @description 根据商品id数组获取购物车商品信息
     * @author maodi
     * @createDate 2018/10/17 15:00
     */
    @Override
    public List<SimpleCommodityDto> getShoppingCarCommodityListByIds(String userId, String[] ids) {
        List<SimpleCommodityDto> result = geneticTestingOrderCarPersistence.getShoppingCarCommodityListByIds(userId,
                ids);
        dealResult(result, userId);
        for (SimpleCommodityDto dto : result) {
            String oldUrl = dto.getCommodityImagesUrl();
            String newUrl = QiniuCertificateUtil.getDownloadCertificateStr(oldUrl);
            dto.setCommodityImagesUrl(newUrl);
        }
        return result;
    }

    /**
     * @param userId        用户id
     * @param ids           商品id数组
     * @param isShoppingCar 是否从购物车购买
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @description 根据商品id数组获取购物车商品结算信息
     * @author maodi
     * @createDate 2018/10/17 15:17
     */
    @Override
    public Map<String, Object> getShoppingCarCommodityBalanceByIds(String userId, String[] ids, String isShoppingCar) {
        if ("0".equals(isShoppingCar)) {
            userId = null;
        }
        return geneticTestingOrderCarPersistence.getShoppingCarCommodityBalanceByIds(userId, ids);
    }


    /**
     * @param userId 用户id
     * @param ids    商品id数组
     * @return java.util.List<com.hsgene.order.domain.applets.AppletsOrderPackageInfoDto>
     * @description 根据商品id数组获取小程序订单商品信息
     * @author maodi
     * @createDate 2018/10/18 11:27
     */
    @Override
    public List<AppletsOrderPackageInfoDto> getAppletsOrderPackageInfoDtosByIds(String userId, String[] ids) {
        return geneticTestingOrderCarPersistence.getAppletsOrderPackageInfoDtosByIds(userId, ids);
    }

    /**
     * @param packageId 商品id
     * @param userId    用户id
     * @return int
     * @description 根据商品id和用户id查找数量
     * @author maodi
     * @createDate 2018/10/15 13:37
     */
    @Override
    public int getCountByPackageIdAndUserId(String packageId, String userId) {
        return geneticTestingOrderCarPersistence.getCountByPackageIdAndUserId(packageId, userId);
    }

    /**
     * @param geneticTestingOrderCarCondition 购物车查询条件
     * @return java.util.List<com.hsgene.shoppingcar.domain.GeneticTestingOrderCar>
     * @description 根据用户id获取购物车列表信息
     * @author maodi
     * @createDate 2018/10/15 10:44
     */
    @Override
    public List<GeneticTestingOrderCar> getGeneticTestingOrderCarByUserId(GeneticTestingOrderCarCondition
                                                                                  geneticTestingOrderCarCondition) {
        return geneticTestingOrderCarPersistence.getGeneticTestingOrderCarByUserId(geneticTestingOrderCarCondition);
    }

    /**
     * @param userId 用户id
     * @param id     购物车id
     * @return com.hsgene.shoppingcar.domain.GeneticTestingOrderCar
     * @description 根据用户id和购物车id查询购物车信息
     * @author maodi
     * @createDate 2018/10/18 13:38
     */
    @Override
    public GeneticTestingOrderCar getGeneticTestingOrderCarById(String userId, String id) {
        return geneticTestingOrderCarPersistence.getGeneticTestingOrderCarById(userId, id);
    }

    /**
     * @param geneticTestingOrderCar
     * @return void
     * @description 新增购物车信息
     * @author maodi
     * @createDate 2018/10/15 10:44
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public void insertGeneticTestingOrderCar(GeneticTestingOrderCar geneticTestingOrderCar) {
        geneticTestingOrderCarPersistence.insertGeneticTestingOrderCar(geneticTestingOrderCar);
    }

    /**
     * @param id         购物车表主键id
     * @param deleteType 删除类型（0手动删除 1购物车结算删除）
     * @param date       更新时间
     * @return void
     * @description 根据id删除购物车信息
     * @author maodi
     * @createDate 2018/10/15 10:44
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public void deleteGeneticTestingOrderCar(String id, int deleteType, Date date) {
        geneticTestingOrderCarPersistence.deleteGeneticTestingOrderCar(id, deleteType, date);
    }

    /**
     * @param userId  用户id
     * @param id      购物车表主键id
     * @param checked 购物车表数据是否勾选
     * @param date    更新时间
     * @return void
     * @description 更新购物车表数据是否勾选
     * @author maodi
     * @createDate 2018/10/15 11:54
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public void updateChecked(String userId, String id, int checked, Date date) {
        geneticTestingOrderCarPersistence.updateChecked(userId, id, checked, date);
    }

    /**
     * @param checked 购物车表数据是否勾选
     * @param userId  用户id
     * @param ids     购物车表主键id数组
     * @return void
     * @description 批量更新购物车勾选状态
     * @author maodi
     * @createDate 2018/12/29 11:16
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public void updateCheckedMulti(int checked, String userId, String[] ids) {
        geneticTestingOrderCarPersistence.updateCheckedMulti(checked, new Date(), userId, ids);
    }

    /**
     * @param userId        用户id
     * @param ids           商品id数组
     * @param isShoppingCar 是否从购物车购买
     * @return java.util.List<com.hsgene.coupon.dto.GeneticUserDiscountDto>
     * @description 获取购物车优惠券列表
     * @author maodi
     * @createDate 2018/11/15 15:02
     */
    @Override
    public List<GeneticUserDiscountDto> getShoppingCarDiscounts(String userId, String[] ids, String isShoppingCar) {
        String uUserId = userId;
        if ("0".equals(isShoppingCar)) {
            uUserId = null;
        }
        Map<String, Object> balance = geneticTestingOrderCarPersistence.getShoppingCarCommodityBalanceByIds(uUserId,
                ids);
        double price = Double.valueOf(balance.get("showPrice").toString());
        List<GeneticUserDiscountDto> discountList = geneticTestingOrderCarPersistence.queryShoppingCarDiscount(userId,
                price, new Date());
        boolean setDefault = false;
        for (GeneticUserDiscountDto geneticDiscountDto : discountList) {
            if (!setDefault) {
                geneticDiscountDto.setIsDefault(1);
                setDefault = true;
            } else {
                geneticDiscountDto.setIsDefault(0);
            }
        }
        return discountList;
    }

    /**
     * @param result 查询结果
     * @param userId 用户id
     * @return void
     * @description 处理查询结果
     * @author maodi
     * @createDate 2018/10/17 14:44
     */
    private void dealResult(List<SimpleCommodityDto> result, String userId) {
        if (!CollectionUtils.isEmpty(result)) {
            ApiResult<List<GeneticDiscountDto>> discountResult = discountCouponService.queryEffectiveDiscount
                    (ClientType.APPLETS.getCode(), userId, null, false, 1, 10);
            if (!discountResult.isSucc()) {
                LOGGER.error(discountResult.getDesc());
            }
            if (!CollectionUtils.isEmpty(discountResult.getData())) {
                List<String> discountTags = discountResult.getData().stream().map(e -> e.getConditionPrice().intValue
                        () + "减" + e.getDiscountPrice().intValue()).collect(Collectors.toList());
                result.forEach(e -> e.setDiscountTags(discountTags));
            }
        }
    }

    /**
     * @param id     优惠券id
     * @param price  价格
     * @param userId 用户id
     * @return com.hsgene.shoppingcar.dto.DiscountDto
     * @description 查询优惠券信息
     * @author maodi
     * @createDate 2019/1/2 19:05
     */
    @Override
    public DiscountDto queryDiscountInfo(String id, Double price, String userId) {
        return geneticTestingOrderCarPersistence.queryDiscountInfo(id, new Date(), price, userId);
    }

    /**
     * @param ids
     * @return java.lang.Integer
     * @description 根据商品id获取是否有下架的商品
     * @author maodi
     * @createDate 2019/1/7 21:15
     */
    @Override
    public Integer queryShelfDownCount(String[] ids) {
        return geneticTestingOrderCarPersistence.queryShelfDownCount(ids);
    }
}
